package data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import dataTransferObject.Categoria; 

public class JDBCCategoriaDAO implements ICategoriaDAO {

	public List<Categoria> selectAllCategorias() {
		Connection conn = ConnectionManager.getInstance().CheckOut();
		PreparedStatement stmt = null;
		List<Categoria> listResult = new LinkedList<Categoria>();
		String sql = "SELECT * FROM categoria";
		ResultSet result = null;
		
		try {
			stmt = conn.prepareStatement(sql);
			result = stmt.executeQuery();
			
			while (result.next()) {
				Categoria transfer = new Categoria();
				transfer.setIdCategoria(result.getInt("ID_CATEGORIA"));
				transfer.setNombre(result.getString("NOMBRE"));
				listResult.add(transfer);
			}
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			ConnectionManager.getInstance().CheckIn(conn);
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (Exception e) {
			}
		}
		return listResult;
	}
	
	public Categoria selectCategoria(int idCategoria) {
		Connection conn = ConnectionManager.getInstance().CheckOut();
		PreparedStatement stmt = null;
		Categoria transfer = new Categoria();
		String sql = "SELECT * FROM categoria WHERE ID_CATEGORIA = ?";
		ResultSet result = null;
		
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, idCategoria);
			result = stmt.executeQuery();
			
			if (result.next()) {
				transfer.setIdCategoria(result.getInt("ID_CATEGORIA"));
				transfer.setNombre(result.getString("NOMBRE"));
			}
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			ConnectionManager.getInstance().CheckIn(conn);
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (Exception e) {
			}
		}
		return transfer;
	}
}
